package com.zhuhjay.controller;

import com.github.benmanes.caffeine.cache.Cache;
import com.google.code.kaptcha.Producer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

import static com.zhuhjay.constant.CacheConstant.KAPTCHA_CACHE_PREFIX;

/**
 * @author ZhuHJay
 * @date 2023/4/25 22:24
 */
@RestController
public class CommonController {

    @Resource
    private Producer kaptcha;

    @Resource
    private Cache<String, String> codeCache;

    @GetMapping("common/kaptcha")
    public void kaptcha(HttpSession session, HttpServletResponse response){
        // 生成验证码响应头
        response.setDateHeader("Expires",0);
        // 禁止缓存
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        response.setHeader("Cache-Control","post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");
        // 响应类型
        response.setContentType("image/png");
        // 生成验证码
        String text = kaptcha.createText();
        codeCache.put(KAPTCHA_CACHE_PREFIX + session.getId(), text);
        BufferedImage image = kaptcha.createImage(text);
        try {
            ImageIO.write(image, "png", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().flush();
                response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
